<?php
namespace lib;

class Encoder{

	static function hash2($uin, $vf){
		$ptb = [];
		$uin = (string)$uin;
		for ($i = 0; $i < strlen($vf); $i++){
			$ptbIndex = $i % 4;
			$ptb[$ptbIndex] ^= self::get_bianma($vf[$i]);
		}
		$salt = ["EC", "OK"];
		$uinByte = [];
		$uinByte[0] = ((($uin >> 24) & 0xFF) ^ self::get_bianma($salt[0][0]));
		$uinByte[1] = ((($uin >> 16) & 0xFF) ^ self::get_bianma($salt[0][1]));
		$uinByte[2] = ((($uin >> 8) & 0xFF) ^ self::get_bianma($salt[1][0]));
		$uinByte[3] = (($uin & 0xFF) ^ self::get_bianma($salt[1][1]));
		$result = [];
		for ($i = 0; $i < 8; $i ++){
			if ($i % 2 == 0)
				$result[$i] = $ptb[$i >> 1];
			else
				$result[$i] = $uinByte[$i >> 1];
		}
		return self::byte2hex($result);
	}

	static function byte2hex($bytes){  //bytes array
		$hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
		$buf = "";

		for ($i = 0; $i < count($bytes); $i ++){
			$buf .= ($hex[($bytes[$i] >> 4) & 0xF]);
			$buf .= ($hex[$bytes[$i] & 0xF]);
		}
		return $buf;
	}

	static function hash33 ($str) {
		for ($t = 0, $e = 0, $n = strlen($str); $e < $n; ++$e) $t += ($t << 5) + hexdec(bin2hex($str[$e]));
		return 2147483647 & $t;
	}

	static function get_bianma($str)//等同于js的charCodeAt()
	{
		$result = array();
		for($i = 0, $l = mb_strlen($str, 'utf-8');$i < $l;++$i)
		{
			$result[] = self::uniord(mb_substr($str, $i, 1, 'utf-8'));
		}
		return join(",", $result);
	}

	static function uniord($str, $from_encoding = false)
	{
		$from_encoding = $from_encoding ? $from_encoding : 'UTF-8';
		if (strlen($str) == 1)
			return ord($str);
		$str = mb_convert_encoding($str, 'UCS-4BE', $from_encoding);
		$tmp = unpack('N', $str);
		return $tmp[1];
	}

	static function times(){
		$time = explode('.', microtime(true));
		$time = str_pad($time[0], 13, $time[1]);
		return $time;
	}

}